import pandas as pd
import numpy as np
import matplotlib as mpl

import matplotlib.pyplot as plt
from matplotlib import colors

# RGB格式颜色转换为16进制颜色格式
def RGB_to_Hex(rgb):
    RGB = rgb.split(',')  # 将RGB格式划分开来
    color = '#'
    for i in RGB:
        num = int(i)
        # 将R、G、B分别转化为16进制拼接转换并大写  hex() 函数用于将10进制整数转换成16进制，以字符串形式表示
        color += str(hex(num))[-2:].replace('x', '0').upper()
    print(color)
    return color


# RGB格式颜色转换为16进制颜色格式
def RGB_list_to_Hex(RGB):
    # RGB = rgb.split(',')  # 将RGB格式划分开来
    color = '#'
    for i in RGB:
        num = int(i)
        # 将R、G、B分别转化为16进制拼接转换并大写  hex() 函数用于将10进制整数转换成16进制，以字符串形式表示
        color += str(hex(num))[-2:].replace('x', '0').upper()
    print(color)
    return color


# 16进制颜色格式颜色转换为RGB格式
def Hex_to_RGB(hex):
    r = int(hex[1:3], 16)
    g = int(hex[3:5], 16)
    b = int(hex[5:7], 16)
    rgb = str(r) + ',' + str(g) + ',' + str(b)
    print(rgb)
    return rgb, [r, g, b]


# 生成渐变色
def gradient_color(color_list, color_sum=6):
    color_center_count = len(color_list)
    # if color_center_count == 2:
    #     color_center_count = 1
    color_sub_count = int(color_sum / (color_center_count - 1))
    color_index_start = 0
    color_map = []
    for color_index_end in range(1, color_center_count):
        color_rgb_start = Hex_to_RGB(color_list[color_index_start])[1]
        color_rgb_end = Hex_to_RGB(color_list[color_index_end])[1]
        r_step = (color_rgb_end[0] - color_rgb_start[0]) / color_sub_count
        g_step = (color_rgb_end[1] - color_rgb_start[1]) / color_sub_count
        b_step = (color_rgb_end[2] - color_rgb_start[2]) / color_sub_count
        # 生成中间渐变色
        now_color = color_rgb_start
        color_map.append(RGB_list_to_Hex(now_color))
        for color_index in range(1, color_sub_count):
            now_color = [now_color[0] + r_step, now_color[1] + g_step, now_color[2] + b_step]
            color_map.append(RGB_list_to_Hex(now_color))
        color_index_start = color_index_end
    return color_map

plt.rcParams['font.sans-serif']=['SimHei']

csv_file = "/home/iris/Project/r/whole_MammaryGland.Lactation/plot.csv"
csv_data = pd.read_csv(csv_file, low_memory = False,header=0)#防止弹出警告
csv_df = pd.DataFrame(csv_data)

bp = csv_df.boxplot(column='X1110008P14Rik', by='Group',grid=False,patch_artist=True,sym='.',
                return_type='dict')

input_colors = ["#00e400", "#ffff00", "#ff7e00"]
colors = gradient_color(input_colors,csv_df["Group"].nunique())
print(colors)

# f = bp.keys()[0]
# for box in f['boxes']:
#     box.set(color='b', linewidth=1)  # 箱体边框颜色
#     box.set(facecolor='b', alpha=0.5)  # 箱体内部填充颜色
# for whisker in f['whiskers']:
#     whisker.set(color='k', linewidth=0.5, linestyle='-')
# for cap in f['caps']:
#     cap.set(color='gray', linewidth=2)
# for median in f['medians']:
#     median.set(color='DarkBlue', linewidth=2)
# for flier in f['fliers']:
#     flier.set(marker='o', color='y', alpha=0.5)
# a = 1
# b = 1
# c = bp.keys()
# d = len(c)
# print(c)
# print(d)

for key in bp.keys():
    #boxes窗体
    for item,c in zip(bp[key]['boxes'],colors):
        item.set(color=c,facecolor=c)
    for item,c in zip(bp[key]['fliers'],colors):
        item.set(markeredgecolor=c)
    for item,c in zip(bp[key]['medians'],colors):
        item.set(color=c, linewidth=2)
    for item,c in zip(bp[key]['whiskers'],colors):
        item.set_color(c)
    for item,c in zip(bp[key]['caps'],colors):
        print(c)
        item.set_color(c)



# [[item.set_color('g') for item in bp[key]['boxes']] for key in bp.keys()]
# # seems to have no effect
# [[item.set_color('r') for item in bp[key]['fliers']] for key in bp.keys()]
# [[item.set_color('g') for item in bp[key]['medians']] for key in bp.keys()]
# [[item.set_markerfacecolor('k') for item in bp[key]['means']] for key in bp.keys()]
# [[item.set_color('g') for item in bp[key]['whiskers']] for key in bp.keys()]
# [[item.set_color('g') for item in bp[key]['caps']] for key in bp.keys()]
plt.suptitle("")
plt.xticks(rotation=-90)
plt.ylabel("Log (TPM)")
plt.xlabel("")
plt.show()

# norm = colors.Normalize(vmin=csv_df.min("X0610007P14Rik"), vmax=csv_df.max("X0610007P14Rik"))
# plt.scatter(csv_df["tsne1"], csv_df["tsne2"], c = csv_df["X0610007P14Rik"], cmap=colormap(), alpha=0.8)
# plt.colorbar()
# plt.xlabel("tsne1")
# plt.ylabel("tsne2")

# csv_df.plot.scatter(x='tsne1', y='tsne2',c="X0610007P14Rik", colormap='viridis')




# ————————————————
# 版权声明：本文为CSDN博主「立志成为摄影师的健身虾」的原创文章，遵循CC 4.0 BY-SA版权协议，转载请附上原文出处链接及本声明。
# 原文链接：https://blog.csdn.net/weekdawn/java/article/details/81389234